package handler

import (
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/service"
	"fitness/go-admin/pkg/response"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type MembershipCardHandler struct {
	service service.MembershipCardService
}

func NewMembershipCardHandler(service service.MembershipCardService) *MembershipCardHandler {
	return &MembershipCardHandler{service: service}
}

// ==================== 卡类型管理 ====================

// CreateCardType 创建卡类型
func (h *MembershipCardHandler) CreateCardType(c *gin.Context) {
	var req model.CardTypeCreateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	if err := h.service.CreateCardType(&req); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "创建成功")
}

// UpdateCardType 更新卡类型
func (h *MembershipCardHandler) UpdateCardType(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.CardTypeUpdateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	if err := h.service.UpdateCardType(uint(id), &req); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "更新成功")
}

// DeleteCardType 删除卡类型
func (h *MembershipCardHandler) DeleteCardType(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	if err := h.service.DeleteCardType(uint(id)); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "删除成功")
}

// GetCardType 获取卡类型详情
func (h *MembershipCardHandler) GetCardType(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	cardType, err := h.service.GetCardType(uint(id))
	if err != nil {
		response.Error(c, 404, "卡类型不存在")
		return
	}

	response.Success(c, cardType, "获取成功")
}

// ListCardTypes 获取卡类型列表
func (h *MembershipCardHandler) ListCardTypes(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	var cardType *model.CardType
	if typeStr := c.Query("type"); typeStr != "" {
		ct := model.CardType(typeStr)
		cardType = &ct
	}

	var isActive *bool
	if activeStr := c.Query("is_active"); activeStr != "" {
		active := activeStr == "true"
		isActive = &active
	}

	cardTypes, total, err := h.service.ListCardTypes(cardType, isActive, page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, cardTypes, total, page, pageSize, "获取成功")
}

// GetActiveCardTypes 获取启用的卡类型
func (h *MembershipCardHandler) GetActiveCardTypes(c *gin.Context) {
	cardTypes, err := h.service.GetActiveCardTypes()
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, cardTypes, "获取成功")
}

// ==================== 会员卡管理 ====================

// CreateCard 开卡
func (h *MembershipCardHandler) CreateCard(c *gin.Context) {
	var req model.CardCreateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	// 获取当前用户ID（操作员）
	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	card, err := h.service.CreateCard(&req, userID.(uint))
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, card, "开卡成功")
}

// GetCard 获取会员卡详情
func (h *MembershipCardHandler) GetCard(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	card, err := h.service.GetCardDetail(uint(id))
	if err != nil {
		response.Error(c, 404, "会员卡不存在")
		return
	}

	response.Success(c, card, "获取成功")
}

// ListCards 获取会员卡列表
func (h *MembershipCardHandler) ListCards(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	var memberID *uint
	if memberIDStr := c.Query("member_id"); memberIDStr != "" {
		id, err := strconv.ParseUint(memberIDStr, 10, 32)
		if err == nil {
			uid := uint(id)
			memberID = &uid
		}
	}

	cardNo := c.Query("card_no")

	var status *model.CardStatus
	if statusStr := c.Query("status"); statusStr != "" {
		s := model.CardStatus(statusStr)
		status = &s
	}

	expireSoon, _ := strconv.Atoi(c.DefaultQuery("expire_soon", "0"))

	cards, total, err := h.service.ListCards(memberID, cardNo, status, expireSoon, page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, cards, total, page, pageSize, "获取成功")
}

// RenewCard 续卡
func (h *MembershipCardHandler) RenewCard(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.CardRenewReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	if err := h.service.RenewCard(uint(id), &req, userID.(uint)); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "续卡成功")
}

// FreezeCard 冻结/解冻卡
func (h *MembershipCardHandler) FreezeCard(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.CardFreezeReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	if err := h.service.FreezeCard(uint(id), &req, userID.(uint)); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	action := "冻结"
	if req.Action == "UNFREEZE" {
		action = "解冻"
	}
	response.Success(c, nil, action+"成功")
}

// CancelCard 注销卡
func (h *MembershipCardHandler) CancelCard(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.CardCancelReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	if err := h.service.CancelCard(uint(id), &req, userID.(uint)); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "注销成功")
}

// ==================== 充值消费 ====================

// Recharge 充值
func (h *MembershipCardHandler) Recharge(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.RechargeReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	resp, err := h.service.Recharge(uint(id), &req, userID.(uint))
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, resp, "充值成功")
}

// Consume 消费
func (h *MembershipCardHandler) Consume(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.ConsumeReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	resp, err := h.service.Consume(uint(id), &req, userID.(uint))
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, resp, "消费成功")
}

// GetRechargeRecords 获取充值记录
func (h *MembershipCardHandler) GetRechargeRecords(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	records, total, err := h.service.GetRechargeRecords(uint(id), page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, records, total, page, pageSize, "获取成功")
}

// GetConsumptionRecords 获取消费记录
func (h *MembershipCardHandler) GetConsumptionRecords(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	var consumeType *model.ConsumeType
	if typeStr := c.Query("consume_type"); typeStr != "" {
		ct := model.ConsumeType(typeStr)
		consumeType = &ct
	}

	records, total, err := h.service.GetConsumptionRecords(uint(id), consumeType, page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, records, total, page, pageSize, "获取成功")
}

// ==================== 查询统计 ====================

// GetMyCard 获取当前用户的会员卡信息
func (h *MembershipCardHandler) GetMyCard(c *gin.Context) {
	// 获取当前用户ID
	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	card, err := h.service.GetMyCard(userID.(uint))
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, card, "获取成功")
}

// GetMyTransactions 获取当前用户的交易记录
func (h *MembershipCardHandler) GetMyTransactions(c *gin.Context) {
	// 获取当前用户ID
	userID, exists := c.Get("userID")
	if !exists {
		response.Error(c, 401, "未授权")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	records, total, err := h.service.GetMyTransactions(userID.(uint), page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, records, total, page, pageSize, "获取成功")
}

// GetBalance 查询余额
func (h *MembershipCardHandler) GetBalance(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	balance, err := h.service.GetBalance(uint(id))
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, balance, "获取成功")
}

// GetBalanceLogs 余额变动日志
func (h *MembershipCardHandler) GetBalanceLogs(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	logs, total, err := h.service.GetBalanceLogs(uint(id), page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, logs, total, page, pageSize, "获取成功")
}

// GetStatistics 消费统计
func (h *MembershipCardHandler) GetStatistics(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var startDate, endDate *time.Time
	if startStr := c.Query("start_date"); startStr != "" {
		if t, err := time.Parse("2006-01-02", startStr); err == nil {
			startDate = &t
		}
	}
	if endStr := c.Query("end_date"); endStr != "" {
		if t, err := time.Parse("2006-01-02", endStr); err == nil {
			endDate = &t
		}
	}

	stats, err := h.service.GetStatistics(uint(id), startDate, endDate)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, stats, "获取成功")
}
